//
//  StoreKitContext.m
//  Stock
//
//  Created by sun black on 11-11-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "StoreKitContext.h"
#import "ASIFormDataRequest.h"
#import "UIDevice+IdentifierAddition.h"
#import "StockAppDelegate.h"


#define didSendPurchageKey   @"didSendPurchage"
#define receiptKey          @"receipt"
#define didRestoreKey       @"didRestore"

@implementation StoreKitContext


-(void)queryProducts{
    NSSet *set = [NSSet setWithObjects:@"H1_Card",nil];
    SKProductsRequest *request = [[[SKProductsRequest alloc] initWithProductIdentifiers:set] autorelease];
    request.delegate = self;
    [request start];
}

-(void)purchaseProduct:(NSString *)productId{
    SKPayment *payment = [SKPayment paymentWithProductIdentifier:productId];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}


- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *products = response.products;
    [self.delegate requestFinishedWithResult:products andUserinfo:[NSDictionary dictionaryWithObject:kQueryProducts forKey:kASIHttpRequestUserinfoKey]];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                    
                    [self verifyReceipt:transaction.transactionReceipt];
                    
                    [self tellServerPurchaseSuccess:transaction.payment.productIdentifier receipt:transaction.transactionReceipt isNew:YES];
                }
                break;
            case SKPaymentTransactionStateRestored:{
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                    [self tellServerPurchaseSuccess:transaction.payment.productIdentifier receipt:transaction.transactionReceipt isNew:NO];
                    NSLog(@"SKPaymentTransactionStateRestored");
                }
                break;
            case SKPaymentTransactionStateFailed:{
                    NSLog(@"SKPaymentTransactionStateFailed");
                    [self.delegate requestFinishedwithError:nil andUserinfo:nil];
                }
                break;
            default:
                break;
        } 
    }
}
-(void)tellServerPurchaseSuccess:(NSString *)productId receipt:(NSData *)receipt isNew:(BOOL)isNew{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:receipt forKey:receiptKey];
    [userDefault setBool:NO forKey:didSendPurchageKey];
    [userDefault synchronize];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@srv/iphone/user/recharge?u=%@&c=%@&d=%@&p=%d",kHostName,[StockContext shareInstance].userId,productId,[[UIDevice currentDevice] myDeviceIdentifier],isNew];
    NSLog(@"%@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    /*NSString *str = [[NSString alloc] initWithData:receipt encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    //[request addPostValue:str forKey:@"receipt"];
    [str release];*/
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObject:kPurchaseProduct forKey:kASIHttpRequestUserinfoKey];
    [workingRequests addObject:request];
    [request startAsynchronous];
    
}
-(void)verifyReceipt:(NSData *)receipt{
    NSURL *url = [NSURL URLWithString:VerifyReceiptURL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //NSString *str = [[NSString alloc] initWithData:receipt encoding:NSUTF8StringEncoding];
    //NSLog(@"%@",str);
    NSString *body = [NSString stringWithFormat:@"{\"receipt-data\":\"%@\" \"password\":\"%@\"}",[receipt base64EncodedString],ShareSecret];
    [request appendPostData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //[request addPostValue:str forKey:@"receipt-data"];
    //[str release];
    //[request addPostValue:[ShareSecret dataUsingEncoding:NSUTF8StringEncoding] forKey:@"password"];
//    [request set]
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObject:kVerifyReceipt forKey:kASIHttpRequestUserinfoKey];
    [workingRequests addObject:request];
    [request startAsynchronous];
}

-(void)requestFinished:(ASIHTTPRequest *)request{
    NSString *action = [request.userInfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([action isEqualToString:kPurchaseProduct]) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setBool:YES forKey:didSendPurchageKey];
        [userDefault synchronize];
        
        NSDictionary *json = [request.responseString JSONValue];
        NSString *date = [json objectForKey:@"radarExpiryDate"];
        if (date.length>0) {
            [[StockContext shareInstance] updateaRadarDate:date];
        }
        [StockContext shareInstance].paid = 1;
        [StockContext shareInstance].radarDays = 15;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNeedUpdateRadarDateNotification object:nil];
        [self.delegate requestFinishedWithResult:request andUserinfo:request.userInfo];
    }else if ([action isEqualToString:kVerifyReceipt]) {
        NSLog(@"%@",request.responseString);
    }
}
-(void)requestFailed:(ASIHTTPRequest *)request{
    [self.delegate requestFinishedwithError:request.error andUserinfo:request.userInfo];
}


//单例实现
static StoreKitContext *instance = nil;
+(StoreKitContext *)shareInstance{
    @synchronized(self){
        if (instance == nil) {
            instance = [[self alloc] initWithDelegate:nil];
            [[SKPaymentQueue defaultQueue] addTransactionObserver:instance];
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            
            if (![userDefault boolForKey:didRestoreKey]) {
                //[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
                [userDefault setBool:YES forKey:didRestoreKey];
            }
            NSData *receipt = [userDefault dataForKey:receiptKey];
            if (receipt && ![userDefault boolForKey:didSendPurchageKey]) {
                [instance tellServerPurchaseSuccess:@"H1_Card" receipt:receipt isNew:NO];
            }
            [userDefault synchronize];
        }
    }
    return instance;
}

- (id)copyWithZone:(NSZone *)zone{
    return self;
}

- (id)retain{
    return self;
}

- (unsigned)retainCount{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release{
}

- (id)autorelease{
    return self;
}

@end
